import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useLocalStorage } from '@vueuse/core'
import { useCookies } from '@vueuse/integrations/useCookies'


export const useTokenStore = defineStore('token', () => {
    const cookies = useCookies()

    const token = ref(cookies.get('TOKEN'))
    const refresh = ref(cookies.get('REFRESH'))
    const userInfo = useLocalStorage('USERINFO', null)

    const isLogin = computed(() => token.value !== undefined)
    const setTokenRefresh = (newToken, refreshToken) => {
        token.value = newToken
        refresh.value = refreshToken
        cookies.set('TOKEN', newToken)
        cookies.set('REFRESH', refreshToken)
    }

    const clearTokenRefresh = () => {
        token.value = undefined
        refresh.value = undefined
        cookies.remove('TOKEN')
        cookies.remove('REFRESH')
    }

    const getUserInfo = computed(() => JSON.parse(userInfo.value))

    const setUserInfo = (newUserInfo) => {
        userInfo.value = JSON.stringify(newUserInfo)
    }

    const clearUserInfo = () => {
        userInfo.value = null
    }

    const logout = () => {
        clearTokenRefresh()
        clearUserInfo()
    }

    return { 
        token, refresh, isLogin, getUserInfo, 
        setUserInfo, setTokenRefresh, clearTokenRefresh,
        clearUserInfo, logout
    }
})